import random as rand

class PopularityWeightEdgeGen(object):

    def __init__(self, selfLoopWeight, maxPopularity):
        '''
        Constructor
        '''
        
        self.SelfLoopWeight = selfLoopWeight
        self.MaxPopularity = maxPopularity
        
        
    def Apply(self, network):
        
        for agent in network.agentList:
            agent.popularity = rand.randint(1, self.MaxPopularity)
            
        for agent in network.agentList:
            outDegree = network.graph.out_degree([agent])[agent]
            curAgentSelfEdgeWeight = self.selfLoopWeight
            if outDegree == 1:
                curAgentSelfEdgeWeight = 1
            
            popularitySum = 0
            for nbr in network.graph.neighbors_iter(agent):
                if (nbr != agent):
                    popularitySum += nbr.popularity
                
            for nbr in network.graph.neighbors_iter(agent):
                curNbrWeight = 0
                if (nbr == agent):
                    curNbrWeight = float(curAgentSelfEdgeWeight)
                else:
                    curNbrWeight = (1 - curAgentSelfEdgeWeight) * nbr.popularity / float(popularitySum)
                
                network.graph[agent][nbr]["weight"] = curNbrWeight